package com.yaopaikeji.interceptor;

import com.yaopaikeji.constants.Constants;
import com.yaopaikeji.exception.AuthenticationException;
import com.yaopaikeji.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    public static final String toLogin = "/login";

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        logger.debug("检验是否需要登陆验证");

        if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            return true;
        }

        //获取被拦截的类或方法
        final HandlerMethod handlerMethod = (HandlerMethod) handler;
        final Method method = handlerMethod.getMethod();
        final Class<?> clazz = method.getDeclaringClass();
        //如果方法和类上存在注解
        if (clazz.isAnnotationPresent(Auth.class) ||
                method.isAnnotationPresent(Auth.class)) {

            //获取注解
            Auth auth = clazz.getAnnotation(Auth.class) != null ? clazz.getAnnotation(Auth.class) : method.getAnnotation(Auth.class);
            logger.debug("需要登陆验证");

            if (!userService.isLogined()) {//如果没有登陆，就转到登陆页面

                response.sendRedirect(toLogin);
                return false;
            }
            //比对值
            if (Constants.ROLE_ROOT_NAME.equals(auth.value())) {

                logger.debug("需要root权限");
                if (userService.isRoot()) {
                    logger.debug("权限验证通过:root");
                    return true;
                }

                throw new AuthenticationException(Constants.NEED_MORE_AUTH);
            } else if (Constants.ROLE_ADMIN_NAME.equals(auth.value())) {

                logger.debug("需要admin权限");
                if (userService.isAdmin()) {
                    logger.debug("权限验证通过：admin");
                    return true;
                }

                throw new AuthenticationException(Constants.NEED_MORE_AUTH);
            } else if(Constants.ROLE_ADMIN_PLUS.equals(auth.value())){

                logger.debug("至少需要管理员权限");
                if(userService.getCurrentUser().getRoleInfo().getRoleNum() <= Constants.ROLE_ADMIN_NUM){
                    return true;
                }

                throw new AuthenticationException(Constants.NEED_MORE_AUTH);
            } else {

                logger.debug("需要登陆权限");
                if (userService.isLogined()) {
                    logger.debug("用户已经登陆");
                    return true;
                }
            }
        }

        logger.debug("不需要登陆验证");

        return super.preHandle(request, response, handler);
    }
}
